import React from 'react';

const Calendar = ({ 
  events, 
  onSelectEvents, 
  selectedDate: propSelectedDate, 
  onSelectDate 
}) => {
  // 获取当前月份的所有日期
  const getDatesInMonth = () => {
    const year = propSelectedDate.getFullYear();
    const month = propSelectedDate.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    
    const dates = [];
    for (let d = 1; d <= lastDay.getDate(); d++) {
      dates.push(new Date(year, month, d));
    }
    return dates;
  };

  // 检查日期是否相同
  const isSameDay = (date1, date2) => {
    return date1.toDateString() === date2.toDateString();
  };

  // 检查日期是否有事件
  const hasEvents = (date) => {
    return events.some(event => {
      const eventDate = new Date(event.date);
      return isSameDay(eventDate, date);
    });
  };

  const handleDateClick = (date) => {
    onSelectDate(date);
    // 获取选中日期的日程
    const dayEvents = events.filter(event => {
      const eventDate = new Date(event.date);
      return eventDate.toDateString() === date.toDateString();
    });
    // 更新父组件中的选中日程
    onSelectEvents(dayEvents);
  };

  const dates = getDatesInMonth();

  return (
    <div className="calendar">
      <div className="calendar-header">
        <div className="weekday">日</div>
        <div className="weekday">一</div>
        <div className="weekday">二</div>
        <div className="weekday">三</div>
        <div className="weekday">四</div>
        <div className="weekday">五</div>
        <div className="weekday">六</div>
      </div>
      <div className="calendar-grid">
        {/* 添加空白天数以对齐第一天 */}
        {Array(dates[0].getDay()).fill(null).map((_, index) => (
          <div key={`empty-${index}`} className="calendar-day empty"></div>
        ))}
        {dates.map((date, index) => (
          <div
            key={index}
            className={`calendar-day ${
              isSameDay(date, propSelectedDate) ? 'selected' : ''
            }`}
            onClick={() => handleDateClick(date)}
          >
            <span>{date.getDate()}</span>
            {hasEvents(date) && <div className="event-dot"></div>}
          </div>
        ))}
      </div>
    </div>
  );
};

export default Calendar; 